<?php

namespace addons\yiliao\controller\api;

use addons\yiliao\controller\api\Doctor as ApiDoctor;
use app\common\exception\UploadException;
use app\common\library\Upload;
use think\Config;
use think\Hook;
use think\App;
use think\Db;

use app\admin\model\yiliao\Notice;
use app\admin\model\yiliao\Pro;
use app\admin\model\yiliao\Faq;
use app\admin\model\yiliao\Address;
use app\admin\model\yiliao\Newscate;
use app\admin\model\yiliao\News;
use app\admin\model\yiliao\Shop;
use app\admin\model\yiliao\Promotion;
use app\admin\model\yiliao\Doctor;
use app\admin\model\yiliao\Booking;
use app\admin\model\yiliao\Procate;
use app\admin\model\yiliao\User;
use app\admin\model\yiliao\Usercoupon;
use app\admin\model\yiliao\Order;

use EasyWeChat\Factory;
use EasyWeChat\BasicService\Jssdk\Client;

use app\common\library\Robot;
class Common extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }
	public function getParam()
	{
		$ret=[];
		$ret['appid'] = $this->setting['appid'];
		$this->success('', $ret);
	}
    public function shoplist()
    {
        $rows = Shop::where(['status'=>'normal'])->order("weigh desc,id desc")->field("id,name,mobile,address,jing,wei,times")->select();
        $this->success('', $rows);
    }
    public function invite()
    {
        $setting = $this->setting;
        $isminapp = $this->request->param('isminapp');
        $ret=[];
        $ret['yqbgimg'] = cdnurl($setting['yqbgimg'], true);
        $ret['yqimg'] = cdnurl($setting['yqimg'], true);
        $ret['yqfen'] = $setting['yqfen'];
        $ret['yqtitle'] = $setting['yqtitle'];
        $ret['yqguize'] = $setting['yqguize'];
        //海报
        //海报
        $data = User::where(['id'=>$this->user['userid']])->find();
        $ret['userid'] =$this->user['userid'];
        $ret['nickname']=$data['nickname'];
        if ($isminapp==1) {
            //生成二维码
            ///www/wwwroot/xx/public
            $document_path = request()->server('DOCUMENT_ROOT');
            $path = '/uploads/yiliao/'.md5($this->user['userid']).'.jpg';
            if (!file_exists($document_path.$path)) {
                $access = $this->getaccess();
                $api = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access['access_token'];
                $can = [];
                $can['page']='pages/index/index';
                $can['scene']="parentid=".$this->user['userid'];
                $can['check_path']=false;
                $can['auto_color']=false;
                $can['width']=430;
                //$can['env_version']='develop';
                $res = Http::post($api, json_encode($can));

                if (!is_dir($document_path.'/uploads/yiliao')) {
                    mkdir(iconv("UTF-8", "GBK", $document_path.'/uploads/yiliao'), 0777, true);
                }
                $file = fopen($document_path.$path, "w");//创建件准备写入
                fwrite($file, $res);//写入
                fclose($file);//关闭
            }
            $ret['ewm']=$this->apiurl.$path;
        } else {
            $ret['ewm']=$this->apiurl."?parentid=".$this->user['userid'];
        }
        $this->success('', $ret);
    }
    public function iinfo()
    {
        $d = [];
        $d['updatetime'] = time();
        $d['nickname'] = $this->request->param('nickname');
        $d['sex'] = '';//$this->request->param('sex');
        $d['birthday'] = '';//$this->request->param('birthday');
        $d['avatar'] = $this->request->param('avatar');
        $res = User::where(['id'=>$this->user['userid']])->update($d);
        if ($res) {
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }
    }
    public function upload()
    {
        $file = $this->request->file('file');
        $fileInfo = $file->getInfo();
        // 获取MIME类型
        $mimetype = $fileInfo['type'];
       
        if (in_array($mimetype, ['image/jpeg', 'image/png', 'image/gif'])) {
            $uploadConfig = Config::get("upload");
            // 兼容云存储上传
            if ($uploadConfig['storage'] != 'local') {
                // 这里可以修改允许上传文件的后缀或修改存储的文件路径，例如只允许上传图片
                set_addon_config($uploadConfig['storage'], ['savekey' => '/uploads/{year}{mon}{day}/{filemd5}{.suffix}', 'mimetype' => 'jpg,png,bmp,jpeg,gif'], false);

                // 添加允许上传的行为
                Hook::add('upload_config_checklogin', function () {
                    return true;
                });
                request()->param('isApi', true);
                //\addons\qiniu\controller\Index
                App::invokeMethod(["\\addons\\{$uploadConfig["storage"]}\\controller\\Index", "upload"], ['isApi' => true]);
            } else {
                // 这里可以修改允许上传文件的后缀或修改存储的文件路径，例如只允许上传图片
                //Config::set('upload', array_merge($uploadConfig, ['savekey' => '/uploads/{year}{mon}{day}/{filemd5}{.suffix}', 'mimetype' => 'jpg,png,bmp,jpeg,gif']));
                $attachment = null;
                // 默认普通上传文件
                try {
                    $upload = new Upload($file);
                    $attachment = $upload->upload();
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                return json(['code'=>1, 'msg'=>'success', 'data'=>['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]]);
            }
        } else {
            $this->error("filetype error");
        }
    }

    public function hxorder()
    {
        $keyword = $this->request->param('keyword');
        $where = [];
        $where['hxuserid']=$this->user['userid'];
        if ($keyword) {
            $where['name|orderid']=['like',"%$keyword%"];
        }
        $rows= Order::where($where)->order("id desc")->select();
        $this->success('', $rows);
    }
    public function jweixin()
    {
        $url = $this->request->param('surl');
        $setting = $this->setting;
        $config = [
            'app_id' => $setting['gzhappid'],
            'secret' => $setting['gzhsecret'],
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];
 
        $app    = Factory::officialAccount($config);
 
        if ($url) {
            $app->jssdk->setUrl(urldecode($url));
        }
        $data = json_decode($app->jssdk->buildConfig(array('updateAppMessageShareData', 'updateTimelineShareData', 'openLocation'), false), true);
        $this->success("获取成功", $data);
    }

    public function zhuanfa()
    {
        $setting = $this->setting;
        $ret=[];
		if ($setting['homeimg']) {
			$ret['homeimg'] = cdnurl($setting['homeimg'], true);
		} else {
			$ret['homeimg'] = "";
		}
        
        $ret['zftitle'] = $setting['zftitle'];
        $ret['zfimg'] = cdnurl($setting['zfimg'], true);
        $ret['kefu'] = '';//$setting['kefu'];
        $this->success('', $ret);
    }
    
    /**
     * 优惠券核销员
     */
    public function orderHexiao()
    {
        $id = $this->request->param('id');
        $user = User::where(['id'=>$this->user['userid']])->find();
        if ($user['orderdata'] == 1) {
            $row = Order::where(['id'=>$id])->find();
            if ($row['status']==1) {
                $res = Order::where(['id'=>$id])->update(['status'=>2, 'hxuserid'=>$this->user['userid'], 'hxtime'=>date("Y-m-d H:i:s")]);
                if ($res) {
                    $this->success('核销成功', $row['name']);
                } else {
                    $this->error('核销失败');
                }
            } else {
                $this->error("失败:请勿重复核销");
            }
        } else {
            $this->error("您没有核销权限");
        }
    }

    /**
     * 优惠券核销员
     */
    public function couponHexiao()
    {
        $id = $this->request->param('id');
        $user = User::where(['id'=>$this->user['userid']])->find();
        if ($user['coupondata'] == 1) {
            $row = Usercoupon::where(['id'=>$id])->find();
            if ($row['status'] == "hidden") {
                $res = Usercoupon::where(['id'=>$id])->update(['status'=>'normal', 'hxuserid'=>$this->user['userid'], 'hxtime'=>date("Y-m-d H:i:s")]);
                if ($res) {
                    $this->success('核销成功');
                } else {
                    $this->error('核销失败');
                }
            } else {
                $this->error("失败:请勿重复核销");
            }
        } else {
            $this->error("您没有核销权限");
        }
    }

    /**
     * 公告信息
     */
    public function notice()
    {
        $rows = Pro::where(['yiliao_procate_id'=>6])->order("id desc")->limit(5)->select();
//        $rows = Notice::where(['status'=>'normal'])->order("id desc")->limit(15)->field("id,name,desc,createtime")->select();
        $this->success('', $rows);
    }


    /**
     * 公告信息  首页
     */
    public function indexnotice()
    {
        $rows = Pro::where(['yiliao_procate_id'=>6,'isdata'=>'yes'])->order("id desc")->limit(5)->select();
//        $rows = Notice::where(['status'=>'normal'])->order("id desc")->limit(5)->select();
        $this->success('', $rows);
    }

    /**
     * 公告详情
     */
    public function noticedetail()
    {
        $id = $this->request->param('id');
        $row = Pro::where(['id'=>$id, 'status'=>'normal'])->find();
        $row['time']=date("Y-m-d", $row['createtime']);
        $row['cate']= Db::name('yiliao_procate')->where(['id'=>$row['yiliao_procate_id']])->value('name');
        $this->success('', $row);
    }
    
    /**
     * 常见问题
     */
    public function help()
    {
        $rows = Faq::where(['status'=>'normal'])->order("id desc")->field("id,name,createtime")->select();
        $this->success('', $rows);
    }

    /**
     * 常见问题详情
     */
    public function helpdetail()
    {
        $id = $this->request->param('id');
        if ($id == 'xieyi') {
            $row=[];
            $row['name']='用户服务协议';
            $row['content'] = $this->setting['xieyi'];
        } else {
            $row = Faq::where(['id'=>$id, 'status'=>'normal'])->find();
            $row['time']=date("Y-m-d", $row['createtime']);
        }
        
        $this->success('', $row);
    }

    /**
     * 就诊人添加编辑
     */
    public function addAddress()
    {
        $id = $this->request->param('id');
        $name = $this->request->param('name');
        $mobile = $this->request->param('mobile');
        $email = $this->request->param('email');
        $sex = $this->request->param('sex');
        $birthday = $this->request->param('birthday');
        $check = $this->request->param('check');
        
        if ($check == 1) {
            Address::where(['yiliao_user_id'=>$this->user['userid']])->update(['mrdata'=>0]);
        }
        $d=[];
        $d['updatetime']=time();
        $d['name']=$name;
        $d['mobile']=$mobile;
        $d['email']=$email;
        $d['sex']=$sex;
        $d['birthday']=$birthday??'';
        $d['mrdata']=$check;
        if ($id==0) {
            //检查就诊人个数
            $num = Address::where(['yiliao_user_id'=>$this->user['userid']])->count();
            if ($num>=$this->setting['jzrnum']) {
                $this->error("最多添加".$this->setting['jzrnum']."个就诊人");
            }
            $d['createtime'] = time();
            $d['yiliao_user_id'] = $this->user['userid'];
            $res = Address::insert($d);
        } else {
            $res = Address::where(['id'=>$id])->update($d);
        }
        if ($res) {
            $this->success('保存成功');
        } else {
            $this->error('保存失败');
        }
    }
    
    /**
     * 就诊人列表
     */
    public function addressList()
    {
        $rows = Address::where(['yiliao_user_id'=>$this->user['userid']])->order("mrdata asc,id desc")->select();
        $this->success('', $rows);
    }

    public function addressDetail()
    {
        $id = $this->request->param('id');
        $row = Address::where(['id'=>$id,'yiliao_user_id'=>$this->user['userid']])->find();
        $this->success('', $row);
    }

    public function addressDel()
    {
        $id = $this->request->param('id');
        $res = Address::where(['id'=>$id,'yiliao_user_id'=>$this->user['userid']])->delete();
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 健康知识
     */
    public function newscate()
    {
        $data = Newscate::where(['status'=>'normal'])->order("paixu asc")->select();
        $ret = [];
        $ret[]=['id'=>0,'tit'=>'全部','isSelected'=>true];
        foreach ($data as $v) {
            $ret[]=['id'=>$v['id'], 'tit'=>$v['name'],'isSelected'=>false];
        }
        $this->success('success', $ret);
    }

    public function news()
    {
        $cateid = $this->request->param('cateid');
        if ($cateid > 0) {
            $data = News::with(['cate'])->where('news.status', 'normal')->where('yiliao_newscate_id', $cateid)->order('id desc')->select();
        } else {
            $data = News::with(['cate'])->where('news.status', 'normal')->order('id desc')->select();
        }
        foreach ($data as $k => $v) {
            $data[$k]['image']=cdnurl($v['image'], true);
        }
        $this->success('success', $data);
    }

    public function newsdetail()
    {
        $id = $this->request->param('id');
        $data = News::with(['cate'])->where('news.id', $id)->find();
        $data['time'] = date('Y-m-d H:i:s', $data['createtime']);
        $views = $data['views']+1;
        News::where('id', $id)->update(['views'=>$views]);
        $this->success('success', $data);
    }

    //政策详情
    public function policysdetail()
    {
        $id = $this->request->param('id');
        $data = News::with(['cate'])->where('news.id', $id)->find();
        $data['time'] = date('Y-m-d H:i:s', $data['createtime']);
        $views = $data['views']+1;
        News::where('id', $id)->update(['views'=>$views]);
        $this->success('success', $data);
    }


    //知识相关
    public function newsrelate()
    {
        $id = $this->request->param('id');
        $data =News::with(['cate'])->where('news.status', 'normal')->limit(3)->select();
        foreach ($data as $k => $v) {
            $data[$k]['image'] = cdnurl($v['image'], true);
            if ($v['id'] == $id) {
                unset($data[$k]);
            }
        }
        $this->success('success', $data);
    }

    public function getshop()
    {
        $id = 2;//$this->request->param('id');
        $row = Shop::where(['id'=>$id])->find();
        if ($row){
            $row['image'] = cdnurl($row['image'], true);
            $images=explode(",", $row['images']);
            foreach ($images as $k => $v) {
                $images[$k] = cdnurl($v, true);
            }
            $row['images'] = $images;
            $this->success('success', $row);
        } else {
            $this->error('门店不存在');
        }
    }

    public function getshops()
    {
        $rows = Shop::where(['status'=>'normal'])->field("id,name,address,image,desc,mobile,jing,wei")->select();
        foreach ($rows as $k => $v) {
            $rows[$k]['image'] = cdnurl($v['image'], true);
        }
        $this->success('', $rows);
    }

    /**
     * 活动
     */
    public function homePromotion()
    {
        $isshop = $this->request->param('isshop', 0);
        $shopid = $this->request->param('shopid');
		$scene = $this->request->param('scene');
        $where=[];
        $where['A.status']='normal';
        $where['A.homedata']=1;
        if ($isshop==1) {
			if($scene==1154){
				$shop = Shop::where(['status'=>'normal'])->order("weigh desc")->find();
				if($shop){
					$shopid = $shop['id'];
				}
			}
            $where[] = ['exp',Db::raw("FIND_IN_SET('$shopid',P.yiliao_shop_ids)")];
        }

        $rows = Promotion::alias("A")->join("yiliao_pro P", "A.yiliao_pro_id=P.id")->where($where)->order("A.paixu desc,A.id desc")->field("A.id,A.start,A.end,A.name,A.image")->select();
        $date = date("Y-m-d");
        foreach ($rows as $k => $v) {
            $rows[$k]['image'] = cdnurl($v['image'], true);
            if ($v['start'] > $date) {
                $rows[$k]['txt'] = "活动未开始";
            } elseif ($v['end'] < $date) {
                $rows[$k]['txt']='活动已结束';
            } else {
                $rows[$k]['txt']='活动进行中';
            }
        }
        $this->success('', $rows);
    }

    public function promotion()
    {
        $rows = Promotion::where(['status'=>'normal'])->order("paixu desc,id desc")->field("id,start,end,name,image")->select();
        $date = date("Y-m-d");
        foreach ($rows as $k => $v) {
            $rows[$k]['image']=cdnurl($v['image'], true);
            if ($v['start'] > $date) {
                $rows[$k]['txt']="活动未开始";
            } elseif ($v['end'] < $date) {
                $rows[$k]['txt']='活动已结束';
            } else {
                $rows[$k]['txt']='活动进行中';
            }
        }
        $this->success('', $rows);
    }
    
    /**
     * 预约天数
     */
    public function yuyuedays()
    {
        $setting = $this->setting;
        $ret=[];
        for ($i = 1; $i <= $setting['yueyueday']; $i++) {
            $ret[]=date("Y-m-d", strtotime("+".$i." day"));
        }
        $this->success('', $ret);
    }

    /**
     * 预约
     */
    public function yuyue()
    {
        $doctorid = $this->request->param('doctorid');
        $mendianid = $this->request->param('mendianid');
        $cateid = $this->request->param('cateid');
        $jzrid = $this->request->param('jzrid');
        $doctor = Doctor::where(['id'=>$doctorid])->find();
        $shop = Shop::where(['id'=>$mendianid])->find();
        $cate = Procate::where(['id'=>$cateid])->find();
        $name = $this->request->param('name');
        $mobile = $this->request->param('mobile');
        $email = $this->request->param('email');
        $persons = $this->request->param('persons');
        $companyname = $this->request->param('companyname');
        $sex=$this->request->param('sex');
        $birthday = $this->request->param('birthday');
        $date = $this->request->param('date');
        $paytype = $this->request->param('paytype');

        $start = strtotime(date("Y-m-d".' 00:00:00'));
        $end = strtotime(date("Y-m-d".' 23:59:59'));

        $num = Booking::where(['createtime'=>['between',[$start,$end]]])->count();
        Db::startTrans();
        try{
            if ($this->user) {
                if ($jzrid == 0) {
                    $jzr=[];
                    $jzr['createtime']=time();
                    $jzr['updatetime']=time();
                    $jzr['yiliao_user_id']=$this->user['userid'];
                    $jzr['name']=$name;
                    $jzr['mobile']=$mobile;
                    $jzr['sex']=$sex;
                    $jzr['birthday']=$birthday;
                    $jzr['mrdata']=0;
                    Address::insert($jzr);
                    $jzrid = Address::getLastInsID();
                }
                //去重检查
                $yynum = Booking::where(['yiliao_address_id'=>$jzrid,'date'=>$date,'doctorid'=>$doctor['id'],'status'=>['in','1,3']])->count();
                if ($yynum==0) {
                    //$orderid = date("Ymd").str_pad($num+1, 4, '0', STR_PAD_LEFT);
                    $orderid = date("YmdHis").rand(100,999);
                    $auth_code = rand(1000, 9999);
                    $d=[];
                   
                    $d['yiliao_user_id']=$this->user['userid'];
                    $d['orderid']=$orderid;
                    $d['name']=$name;
                    $d['mobile']=$mobile;
                    $d['email']=$email;
                    $d['persons']=$persons;
                    $d['companyname']=$companyname;
                    $d['sex']=$sex;
                    $d['birthday']=$birthday;
                    $d['shopname']=$shop['name'];
                    $d['address']=$shop['address'];
                    $d['yiliao_address_id']=$jzrid;
                    $d['doctorid']=$doctor['id'];
                    $d['doctor']=$doctor['name'];
                    $d['price']=$doctor['price'];
                    $d['date']=$date;
                    $d['times']=$this->request->param('times');
                    $d['desc']=$this->request->param('desc');
                    $d['cate']=$cate['name']??'';
                   
                    $ret=[];
                    if ($doctor['price']>0) {
                        $d['createtime']=0;
                        $d['status']=0;
                       
                        $res = Booking::insert($d);
                        $params = [
                            'amount'=>$doctor['price'],
                            'orderid'=>$orderid,
                            'type'=>'wechat',
                            'title'=>"订单".$orderid,
                            'notifyurl'=>$this->apiurl.'/addons/yiliao/api.order/bookingnotify',
                            'returnurl'=>$this->apiurl.'/addons/yiliao/api.order/bookingnotify',
                            'method'=>$paytype,
                            'openid'=>$this->user['openid'],
                            'auth_code'=>$auth_code
                        ];
                        $data= \addons\epay\library\Service::submitOrder($params);
                        //print_r($data);
                        
                        $ret['timeStamp'] = $data['timeStamp'];
                        $ret['nonceStr'] = $data['nonceStr'];
                        $ret['package'] = $data['package'];
                        $ret['paySign'] = $data['paySign'];
                        $ret['appId'] = $data['appId'];
                        $ret['signType'] = $data['signType'];
                        $ret['status']=0;
                    } else {
                        $d['createtime']=time();
                        $d['status']=1;
                        $ret['status']=1;
                        $res = Booking::insertGetId($d);
                    }
                    Db::commit();
                    //预约成功给企业微信 发送群消息
                    Robot::send_applyed_message($res);
                    $this->success("预约成功", $ret);
                } else {
                    $this->error('请勿重复预约');
                }
            } else {
                $this->error('请先登录');
            }
           
        } catch (\think\exception\ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function myyuyue()
    {
        //就诊人
        $cates = Address::where(['yiliao_user_id'=>$this->user['userid']])->order("mrdata asc,id desc")->select();
        $arr = [];
        $jiuzhenren = [];
        foreach ($cates as $v) {
            $age = date("Y") - date("Y", strtotime($v['birthday']));
            $jiuzhenren[]=['id'=>$v['id'], 'name'=>$v['name'].' / '.$age.'岁'];
            $arr[] = $v['id'];
        }
        $rows=[];
        if (sizeof($jiuzhenren) > 0) {
            $jzrid =$jiuzhenren[0]['id'];
//            $rows=Booking::where(['yiliao_address_id'=>$jzrid])->order("id desc")->select();
            $rows=Booking::where(['yiliao_address_id'=>['in',$arr]])->order("id desc")->select();
        }
        $date=date("Y-m-d");
        foreach ($rows as $k => $v) {
            if ($v['status'] == 2) {
                $rows[$k]['txt']='已取消';
            } elseif ($v['status'] == 3) {
                $rows[$k]['txt']='已完成';
            } else {
                if ($v['date'] < $date) {
                    $rows[$k]['status']=0;
                    $rows[$k]['txt'] = '已过期';
                } else {
                    $rows[$k]['txt'] = '已预约';
                }
            }
        }
        $this->success('', ['cates'=>$jiuzhenren, 'rows'=>$rows]);
    }
    
    public function myyuyueSearch()
    {
        $keyword  = $this->request->param('keyword');
        $id  = $this->request->param('id');
        if ($keyword) {
            $rows=Booking::where(['yiliao_address_id'=>$id, 'cate|doctor'=>['like',"%$keyword%"]])->order("id desc")->select();
        } else {
            $rows=Booking::where(['yiliao_address_id'=>$id])->order("id desc")->select();
        }
        //状态:1=已预约,2=已取消,3=已完成
        $date=date("Y-m-d");
        foreach ($rows as $k => $v) {
            if ($v['status'] == 2) {
                $rows[$k]['txt']='已取消';
            } elseif ($v['status'] == 3) {
                $rows[$k]['txt']='已完成';
            } else {
                if ($v['date'] < $date) {
                    $rows[$k]['status']=0;
                    $rows[$k]['txt']='已过期';
                } else {
                    $rows[$k]['txt']='已预约';
                }
            }
        }
        $this->success('', $rows);
    }

    public function myyuyuedetail()
    {
        $id  = $this->request->param('id');
        $row = Booking::where(['id' => $id,'yiliao_user_id'=>$this->user['userid']])->find();
        $this->success('', $row);
    }

    /**
     * 招商申请入驻
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function applyed()
    {
        $applyed_model = new \app\admin\model\Applyed;
        $param = $this->request->param();

        Db::startTrans();
        try{
            //
            if ($this->user) {
                $param['user_id'] = $this->user['userid'];
                $ret = $applyed_model->allowField(true)->save($param);
                $this->success("申请成功", $ret);
            } else {
                $this->error('请先登录');
            }

        } catch (\think\exception\ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * @return void
     */
    public function proenlist()
    {
        $proenlist_model = new \app\admin\model\yiliao\Proenlist;
        $param = $this->request->param();
        Db::startTrans();
        try{
            //
            if ($this->user) {
                $param['user_id'] = $this->user['userid'];
                $ret = $proenlist_model->allowField(true)->save($param);
                $this->success("报名成功", $ret);
            } else {
                $this->error('请先登录');
            }
        } catch (\think\exception\ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function qxreason()
    {
        $setting = $this->setting;
        //$arr = json_decode($setting['reason'], true);
        $ret=[];
        foreach ($setting['reason'] as $k => $v) {
            $ret[]=['name'=>$v];
        }
        $this->success('', $ret);
    }

    public function quxiao()
    {
        $id  = $this->request->param('id');
        $reason  = $this->request->param('reason');
        $desc  = $this->request->param('desc');
        Db::startTrans();
        try{
            $order = Booking::where(['id'=>$id,'yiliao_user_id'=>$this->user['userid']])->find();
            if ($order['status']==1) {
                $res = Booking::where(['id'=>$id,'yiliao_user_id'=>$this->user['userid']])->update(['reason'=>$reason, 'qxdesc'=>$desc, 'status'=>2]);
                if ($res!==false) {
					if($order['price']>0){
						 $setting = get_addon_config('yiliao');
						$epay = get_addon_config('epay');
						$document_root = request()->server("DOCUMENT_ROOT").'/..';
						//退款处理
						$config = [
							// 必要配置
							'app_id'             => $epay['wechat']['miniapp_id'],
							'mch_id'             => $epay['wechat']['mch_id'],
							'key'                => $epay['wechat']['key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
							
							// 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
							'cert_path'          => $document_root.$epay['wechat']['cert_client'], // XXX: 绝对路径！！！！
							'key_path'           => $document_root.$epay['wechat']['cert_key'],      // XXX: 绝对路径！！！！
							'notify_url'         => '',     // 你也可以在下单时单独设置来想覆盖它
						];
						
						$app = Factory::payment($config);
						// 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
						$refundorderid = date("YmdHis").rand(100, 999);
						$ret = $app->refund->byOutTradeNumber($order['orderid'], $refundorderid, $order['price']*100, $order['price']*100, [
							'refund_desc' => '订单号:'.$order['orderid']
						]);
						if ($ret['result_code']=="SUCCESS") {
							//$params['refund']=$refundorderid;
							Db::commit();
							$this->success("取消成功");
						} else {
							$this->error("错误:".$ret['err_code_des']);
							//throw new \think\Exception("错误:".$ret['err_code_des']);
						}
					} else {
						Db::commit();
                        //取消预约成功给企业微信 发送群消息
                        Robot::send_applyed_message($order['id']);
						$this->success("取消成功");
					}
                } else {
                    $this->error('取消失败');
                }
            } else {
                $this->error('禁止取消');
            }
            
        } catch (\think\exception\ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
    }
}
